<?php

namespace addons\qingdongams\model;


use think\Exception;
use think\Model;
use think\Session;
use traits\model\SoftDelete;

/**
 *员工外勤签到
 */
class StaffSignIn Extends Model {
	use SoftDelete;

    const   WORKORDER_TYPE = 'workorder';//工单
    const   EVENT_TYPE = 'event';//日程
    const   CUSTOMER_TYPE = 'customer';//客户
    const   PROOFING_TYPE = 'proofing';//客户
    const   ORDER_TYPE = 'order';//订单

    protected $name  = 'qingdongams_staff_sign_in';
	// 开启自动写入时间戳字段
	protected $autoWriteTimestamp = 'int';
	// 定义时间戳字段名
	protected $createTime = 'createtime';
	protected $updateTime = 'updatetime';
	protected $deleteTime = 'deletetime';


	//获取创建时间
	public function getCreatetimeAttr($value) {
		return date('Y-m-d H:i:s', $value);
	}

    public function getDistanceAttr($value) {
        return float_number($value);
    }
	//
	public function getFileIdsAttr($value) {
		$files  = explode(',', $value);
		$result = [];
		foreach ($files as $fid) {
			if ($fid) {
				$result[] = cdnurl(File::getUrl($fid), true);
			}
		}

		return $result;
	}

	//获取日程状态
	public function getRelationProcessAttr($value){
        $process=[0=>'未开始',1=>'出发签到',2=>'到达签到',3=>'完成签到',4=>'返程签到'];

        return $process[$value]??$value;
    }

	//签到
	public static function createSignIn($params) {

		$staff              = Staff::info();
		$params['staff_id'] = $staff->id;

		$model = new self;

		$lastSignIn=$model->where(['staff_id'=>$staff->id])->order('id desc')->field('id,lng,lat,location')->find();
        if (empty($lastSignIn['lng']) || empty($lastSignIn['lat']) ||  empty($params['lng'])|| empty($params['lat'])) {
            $params['trip_distance'] = 0;
        } else {
            $params['trip_distance'] = getdistance($lastSignIn['lng'], $lastSignIn['lat'], $params['lng'], $params['lat']);
        }
		// 调用当前模型对应的User验证器类进行数据验证
		$result = $model->allowField(true)->save($params);
		if(!$result){
			throw new Exception('创建签到记录失败');
		}
		$lastId = $model->getLastInsID();
        if (isset($params['reminds_id'])) {//发送通知
            $staff_ids = explode(',', $params['reminds_id']);
            foreach ($staff_ids as $staff_id) {
                //发送通知
                Message::addMessage(Message::SIGN_TYPE, $lastId, $staff_id, $staff->id, $staff->name . '有新的工作动态，由您审阅！');
            }
        }


		return true;
	}


    //创建签到信息
    public static function quickSignIn($customer_id, $content, $params=[])
    {
        $customer = Customer::where(['id' => $customer_id])->field('lng,lat')->find();
        $lng=$params['lng']??'';
        $lat=$params['lat']??'';
        if (empty($lng) && empty($lat)) {
            $distance = '';
        } elseif (empty($customer['lng']) && empty($customer['lat'])) {
            $distance = '';
        } else {
            $distance = getdistance($customer['lng'], $customer['lat'], $lng, $lat);
        }


        $staff = Staff::info();
        $data = [
            'content' => $content,
            'customer_id' => $customer_id,
            'relation_type' => $params['relation_type']??'',
            'relation_id' => $params['relation_id']??'',
            'relation_process' => $params['relation_process']??'工单备注',
            'lng' => $lng,
            'lat' => $lat,
            'distance' => $distance,
            'location' => $params['location']??'',
            'file_ids' => $params['file_ids']??'',
            'staff_id'=>$staff->id,
        ];
        $Enent = new self;

        $result = $Enent->allowField(true)->save($data);
        if (false === $result) {
            // 验证失败 输出错误信息
            throw new Exception($Enent->getError());
        }

        return true;
    }

	//员工
	public function staff() {
		return $this->belongsTo(Staff::class, 'staff_id', 'id')->field('id,name,img,post');
	}

	//客户
	public function customer() {
		return $this->belongsTo(Customer::class, 'customer_id', 'id')->field('id,name');
	}
	//是否跟进
    public function read() {
        return $this->hasMany(StaffSignInRead::class, 'sign_in_id', 'id')->field('sign_in_id,createtime');
    }
    //评论次数
    public function commentNumber(){
	    return $this->belongsTo(Comment::class,'id','relation_id')->where(['relation_type'=>Comment::SIGN_TYPE])->group('relation_id')->field('relation_id,count(*) as comment')->bind('comment');
    }


    //关联工单
    public function workorder() {
        return $this->belongsTo(Workorder::class, 'relation_id', 'id')->field('id,title');
    }

    //关联日程
    public function eventTitle() {
        return $this->belongsTo(Event::class, 'relation_id', 'id')->field('id,title');
    }
}
